package cn.juque.jdfsystem.threads;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.juque.common.constants.StringConstants;
import cn.juque.jdfsystem.entity.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.*;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>DelFileThreadPool</li>
 *     https://blog.csdn.net/qq_38299413/article/details/105758784
 * </ul>
 * @date 2023-12-13 17:39:49
 **/
@Slf4j
@Component("delFileThreadPool")
public class DelFileThreadPool {

    private static final ThreadFactory THREAD_FACTORY = ThreadUtil.newNamedThreadFactory("del-dsc-file-", true);

    private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(2, 200,
            0,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1000), THREAD_FACTORY);

    public void execute(FileInfo fileInfo) {
        EXECUTOR.execute(() -> this.deleteDiskFile(fileInfo));
    }

    public Boolean submit(FileInfo fileInfo) {
        try {
            Future<Boolean> future = EXECUTOR.submit(() -> this.deleteDiskFile(fileInfo));
            return future.get();
        } catch (InterruptedException e) {
            log.error("文件ID:{}, 删除失败", fileInfo.getId(), e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("文件ID:{}, 删除失败", fileInfo.getId(), e);
        }
        return false;
    }

    private boolean deleteDiskFile(FileInfo fileInfo) {
        try {
            String fileName = fileInfo.getId() + StringConstants.POINT + fileInfo.getFileExt();
            File file = FileUtil.file(fileInfo.getServerPath(), fileName);
            FileUtil.del(file);
            return true;
        } catch (Exception e) {
            log.error("文件id:{}, 删除文件失败, msg={}", fileInfo.getId(), e.getMessage());
            return false;
        }
    }
}
